package controller;

import annotation.Controller;
import annotation.DependencyInjection;
import annotation.RequestMapping;
import annotation.Singleton;
import entity.User;
import enums.RequestType;
import enums.ResponseErrorCode;
import exception.ServerException;
import request.user.*;
import response.user.*;
import service.UserService;
import util.StringUtils;

@Singleton
@Controller
public class UserController {
    private UserService userService;

    @DependencyInjection
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(RequestType.UserRegister)
    public UserRegisterResponse register(UserRegisterRequest request) {
        String username = request.getUsername();
        if (!StringUtils.lengthInRange(username, User.USERNAME_MINIMUM_LENGTH, User.USERNAME_MAXIMUM_LENGTH)) {
            throw new ServerException(ResponseErrorCode.ILLEGAL_USERNAME);
        }

        String password = request.getPassword();
        if (!StringUtils.lengthInRange(password, User.PASSWORD_MINIMUM_LENGTH, User.PASSWORD_MAXIMUM_LENGTH)) {
            throw new ServerException(ResponseErrorCode.ILLEGAL_PASSWORD);
        }
        return userService.register(request.getUsername(), request.getPassword(), request.getNickname(), request.getAvatar());
    }

    @RequestMapping(RequestType.UserLogin)
    public UserLoginResponse login(UserLoginRequest request) {
        return userService.login(request.getUsername(), request.getPassword());
    }

    @RequestMapping(RequestType.NicknameChange)
    public NicknameChangeResponse changeNickname(NicknameChangeRequest request) {
        return userService.changeNickname(request.getUsername(), request.getNewNickname());
    }

    @RequestMapping(RequestType.PasswordChange)
    public PasswordChangeResponse changePassword(PasswordChangeRequest request) {
        return userService.changePassword(request.getUsername(), request.getOldPassword(), request.getNewPassword());
    }

    @RequestMapping(RequestType.UserList)
    public UserListResponse getAllUsers(UserListRequest request) {
        return userService.getAllUsers();
    }

    @RequestMapping(RequestType.UserGet)
    public UserGetResponse getUser(UserGetRequest request) {
        return userService.getUser(request.getUsername());
    }
}
